/*
 * Copyright (c) 2013 Acorn International.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http:www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.chinadrtv.batch.admin.controller.ozing;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chinadrtv.user.model.*;
import com.chinadrtv.user.service.UserManager;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.chinadrtv.user.service.ozing.OzingService;

@Controller
public class OzingCardRedeemController {
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
    @Autowired
    private OzingService ozingService;

    @Autowired
    private UserManager userManager;
	
    @RequestMapping(value = "/ozing/card/redeems", method = RequestMethod.GET)
    public String handleCardRedeems() {
        return "ozing/card_redeems";
    }
    
    @RequestMapping(value = "/ozing/redeems/json", method = RequestMethod.GET)
    public String getRedeemsJSON(@RequestParam(required = false, defaultValue = "0") int start_index,
                                  @RequestParam(required = false, defaultValue = "10") Integer num_per_page,
                                  @RequestParam(required = false) String sort,
                                  @RequestParam(required = false) String dir,
                                  String username,
                                  String deviceNumber,
                                  String agent,
                                  String startDate,
                                  String endDate,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
    	String pUsername = StringUtils.isEmpty(username) ? null : username;
    	String pDeviceNumber = StringUtils.isEmpty(deviceNumber) ? null : deviceNumber;
    	String pAgent = StringUtils.isEmpty(agent) ? null : agent;
    	Date pStartDate = StringUtils.isEmpty(startDate) ? null : sdf.parse(startDate);
    	Date pEndDate = StringUtils.isEmpty(endDate) ? null : sdf.parse(endDate);
        List<UserOzingCard> uocList = null;
        JSONArray uocJsonArray = new JSONArray();
        int totalRecords = 0;
        
    	uocList = ozingService.findPaginatedCardRedeem(start_index, num_per_page, sort, dir, pUsername, pDeviceNumber, pAgent, pStartDate, pEndDate);
    		for (UserOzingCard uoc_ : uocList) {
    			uocJsonArray.put(uoc_.to_json());
    		}
    	totalRecords = ozingService.getCardRedeemCount(pUsername, pDeviceNumber, pAgent, pStartDate, pEndDate);
        
        response.setContentType("text/json");
        response.getWriter().print("{\"records\":" + uocJsonArray.toString() + ",\"totalRecords\":" + totalRecords
                + ",\"startIndex\":" + start_index  + ",\"sort\":\"" + sort  + "\",\"dir\":\"" + dir + "\" }");
        response.setHeader("Cache-Control", "no-cache");
        return null;
    }
    
    @RequestMapping(value = "/ozing/card/txs", method = RequestMethod.GET)
    public String handleCardTxs() {
        return "ozing/card_txs";
    }

    @RequestMapping(value = "/ozing/card/freeOrder", method = RequestMethod.GET)
    public String handleCardFreeTxs() {
        return "ozing/card_free_order";
    }

    @RequestMapping(value = "/ozing/card/vipOrder", method = RequestMethod.GET)
    public String handleCardVIPTxs() {
        return "ozing/card_vip_order";
    }
    
    @RequestMapping(value = "/ozing/txs/json", method = RequestMethod.GET)
    public String getTxJSON(@RequestParam(required = false, defaultValue = "0") int start_index,
                                  @RequestParam(required = false, defaultValue = "10") Integer num_per_page,
                                  @RequestParam(required = false) String sort,
                                  @RequestParam(required = false) String dir,
                                  String username,
                                  String deviceNumber,
                                  String agent,
                                  String startDate,
                                  String endDate,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
    	String pUsername = StringUtils.isEmpty(username) ? null : username;
    	String pDeviceNumber = StringUtils.isEmpty(deviceNumber) ? null : deviceNumber;
    	String pAgent = StringUtils.isEmpty(agent) ? null : agent;
    	Date pStartDate = StringUtils.isEmpty(startDate) ? null : sdf.parse(startDate);
    	Date pEndDate = StringUtils.isEmpty(endDate) ? null : sdf.parse(endDate);
        List<UserOzingCardTx> uoctList = null;
        JSONArray uoctJsonArray = new JSONArray();
        int totalRecords = 0;
        
    	uoctList = ozingService.findPaginatedCardTx(start_index, num_per_page, sort, dir, pUsername, pDeviceNumber, pAgent, pStartDate, pEndDate);
    	for (UserOzingCardTx uoct_ : uoctList) {
    		uoctJsonArray.put(uoct_.to_json());
    	}
    	totalRecords = ozingService.getCardTxCount(pUsername, pDeviceNumber, pAgent, pStartDate, pEndDate);
        
        response.setContentType("text/json");
        response.getWriter().print("{\"records\":" + uoctJsonArray.toString() + ",\"totalRecords\":" + totalRecords
                + ",\"startIndex\":" + start_index  + ",\"sort\":\"" + sort  + "\",\"dir\":\"" + dir + "\" }");
        response.setHeader("Cache-Control", "no-cache");
        return null;
    }

    @RequestMapping(value = "/ozing/freeOrder/json", method = RequestMethod.GET)
    public String getFreeOrderJSON(@RequestParam(required = false, defaultValue = "0") int start_index,
                                  @RequestParam(required = false, defaultValue = "10") Integer num_per_page,
                                  @RequestParam(required = false) String sort,
                                  @RequestParam(required = false) String dir,
                                  String username,
                                  String nickname,
                                  String deviceNumber,
                                  String startDate,
                                  String endDate,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
    	String pUsername = StringUtils.isEmpty(username) ? null : username;
    	nickname = StringUtils.isEmpty(nickname) ? null : nickname;
    	String pDeviceNumber = StringUtils.isEmpty(deviceNumber) ? null : deviceNumber;
    	Date pStartDate = StringUtils.isEmpty(startDate) ? null : sdf.parse(startDate);
    	Date pEndDate = StringUtils.isEmpty(endDate) ? null : sdf.parse(endDate);

        List<UserFreeOzingOrder> uoctList = null;
        JSONArray uoctJsonArray = new JSONArray();
        int totalRecords = 0;

    	uoctList = ozingService.findPaginatedFreeOrder(start_index, num_per_page, sort, dir, pUsername, nickname, pDeviceNumber,pStartDate, pEndDate);
        List<User> userList = new ArrayList<User>();
        for (UserFreeOzingOrder uoct_ : uoctList) {
            userList.add(uoct_.getUser());
        }
        Map<Long, String> userDevicesMap = userManager.getUserDevicesMap(userList);
        for (UserFreeOzingOrder uoct_ : uoctList) {
            JSONObject jsonObject = uoct_.toJson();
            if(userDevicesMap.containsKey(uoct_.getUser().getId())){
                jsonObject.put("deviceInfo", userDevicesMap.get(uoct_.getUser().getId()));
            }
            jsonObject.put("firstName", uoct_.getUser().getFirstName());
            uoctJsonArray.put(jsonObject);
        }
    	totalRecords = ozingService.getFreeOrderCount(pUsername, nickname, pDeviceNumber, pStartDate, pEndDate);

        response.setContentType("text/json");
        response.getWriter().print("{\"records\":" + uoctJsonArray.toString() + ",\"totalRecords\":" + totalRecords
                + ",\"startIndex\":" + start_index  + ",\"sort\":\"" + sort  + "\",\"dir\":\"" + dir + "\" }");
        response.setHeader("Cache-Control", "no-cache");
        return null;
    }

    @RequestMapping(value = "/ozing/vipOrder/json", method = RequestMethod.GET)
    public String getVIPOrderJSON(@RequestParam(required = false, defaultValue = "0") int start_index,
                                  @RequestParam(required = false, defaultValue = "10") Integer num_per_page,
                                  @RequestParam(required = false) String sort,
                                  @RequestParam(required = false) String dir,
                                  String username,
                                  String nickname,
                                  String productId,
                                  String deviceNumber,
                                  String agent,
                                  String startDate,
                                  String endDate,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
    	String pUsername = StringUtils.isEmpty(username) ? null : username;
        nickname = StringUtils.isEmpty(nickname) ? null : nickname;
    	productId = StringUtils.isEmpty(productId) ? null : productId;
    	String pDeviceNumber = StringUtils.isEmpty(deviceNumber) ? null : deviceNumber;
        String pAgent = StringUtils.isEmpty(agent) ? null : agent;
    	Date pStartDate = StringUtils.isEmpty(startDate) ? null : sdf.parse(startDate);
    	Date pEndDate = StringUtils.isEmpty(endDate) ? null : sdf.parse(endDate);

        List<UserOzingOrder> uoctList = null;
        JSONArray uoctJsonArray = new JSONArray();
        int totalRecords = 0;

    	uoctList = ozingService.findPaginatedVipOrder(start_index, num_per_page, sort, dir, pUsername, nickname, pDeviceNumber, pAgent, pStartDate, pEndDate, productId);
        List<User> userList = new ArrayList<User>();
        for (UserOzingOrder uoct_ : uoctList) {
            userList.add(uoct_.getUser());
        }
        Map<Long, String> userDevicesMap = userManager.getUserDevicesMap(userList);
    	for (UserOzingOrder uoct_ : uoctList) {
            JSONObject jsonObject = uoct_.toJsonForVip();
            if(userDevicesMap.containsKey(uoct_.getUser().getId())){
                jsonObject.put("deviceInfo", userDevicesMap.get(uoct_.getUser().getId()));
                jsonObject.put("firstName", uoct_.getUser().getFirstName());
            }
            uoctJsonArray.put(jsonObject);
    	}
    	totalRecords = ozingService.getVipOrderCount(pUsername, nickname, pDeviceNumber, pAgent, pStartDate, pEndDate, productId);

        response.setContentType("text/json");
        response.getWriter().print("{\"records\":" + uoctJsonArray.toString() + ",\"totalRecords\":" + totalRecords
                + ",\"startIndex\":" + start_index  + ",\"sort\":\"" + sort  + "\",\"dir\":\"" + dir + "\" }");
        response.setHeader("Cache-Control", "no-cache");
        return null;
    }

}
